import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import {AtTabs, AtTabsPane} from 'taro-ui';
import moment from 'dayjs';

import {View, Image, ScrollView} from '@tarojs/components';
import {
  SECONDS_FORMAT,
  NAVBAR_TITLE,
  OSS_PATH_PREFIX,
  OSS_BASE_PATH_PREFIX,
  GAME_SHARE_TITLE,
  RECORD_STATUS,
} from './constant';
import './index.less';
import 'taro-ui/dist/style/components/tabs.scss';
import PageLoading from '../../common/PageLoading';
import CustomScrollView from '@/common/scrollview';
import 'taro-ui/dist/style/components/flex.scss';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class GoldCoinsDetailPa extends React.Component<Partial<T.IProps>, any> {
  //使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {},
      pics: {
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
        jindou: OSS_PATH_PREFIX + '/detailCoinIcon.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/emptyGrey.png',
      },
      navbarSettings: {
        navBarHeight: 0, // 导航栏高度
        menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
        menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
        menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
      },
      currentStatus: 0, // 选中的tab

      empty: {
        text: '暂无数据',
      },
      loading: {
        status: false,
        text: '',
        style: {
          border: '8rpx solid #ccc',
        },
        textStyle: {
          color: '#ccc',
        },
      },
      refresherTriggered: true,
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.props.actions.init();
  }

  componentDidMount(): void {
    this.getNavHeight();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  /**
   * 获取navbar高度
   */
  getNavHeight() {
    var sysinfo = Taro.getSystemInfoSync();
    const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    let navBarHeight = sysinfo.statusBarHeight + 44;
    let menuRight = sysinfo.screenWidth - menuButtonInfo.right;
    let menuTop = menuButtonInfo.top;
    let menuHeight = menuButtonInfo.height;
    this.setState({
      navbarSettings: {
        ...this.state.navbarSettings,
        navBarHeight, // 导航栏高度
        menuHeight,
        menuTop,
      },
    });
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    // 收藏进来的就直接去首页
    if (params.favorite) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }
    this.handleQuery(); // 查询信息
  };

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    if (nextProps.main.status.loading === false && this.props.main.status.loading == true) {
      this.setState({
        refresherTriggered: false,
      });
    }
  }

  /**
   * 查询信息
   */
  handleQuery() {
    this.handleQueryUserInfo();
    this.handleQueryItems({});
  }

  /**
   * 查询用户信息
   */
  handleQueryUserInfo() {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  }

  /**
   * 查询列表信息
   */
  handleQueryItems(pagination, filterInfo = {}) {
    const {
      main: {page, filter},
    } = this.props;

    // 编辑参数
    const {currentStatus} = this.state;

    console.log('index.tsx handleQueryItems currentStatus', currentStatus);
    let type = RECORD_STATUS[currentStatus].status;
    let params = {
      page: {
        ...page,
        ...pagination,
      },
      filter: {
        ...filter,
        type,
        ...filterInfo,
      },
    };

    console.log('currentStatus', currentStatus, 'params', params);
    this.props.actions.action.loadItems(params);
  }

  render() {
    if (!this.props.main) return null;
    let {
      main: {isLoading},
    } = this.props;
    console.log(isLoading);

    return (
      <View className="pageGoldCoinsDetailPa">
        {this.renderNavBar()}
        {this.renderContent()}
      </View>
    );
  }

  /**
   * 渲染基本信息
   */
  renderNavBar() {
    const {
      navbarSettings: {navBarHeight, menuHeight, menuTop},
    } = this.state;
    return (
      <View className="header">
        <View className="navbar" style={{height: navBarHeight}}>
          <View style={{height: menuHeight, top: menuTop}} className="navBarContent">
            <View className="at-icon at-icon-chevron-left" onClick={this.handleNavBack}></View>
            <View className="navTitle" style={{fontSize: '36rpx'}}>
              {NAVBAR_TITLE}
            </View>
          </View>
        </View>
      </View>
    );
  }

  /**
   * 渲染列表
   * @returns
   */
  renderContent() {
    const {
      main: {
        status: {loading},
        items,
        userInfo,
      },
    } = this.props;
    const {
      pics: {jindou},
    } = this.state;

    return (
      <>
        <View className="detailContent">
          <View className="userInfo at-row">
            <View className="at-col at-col-4 info">
              <View className="title">我的魔力豆</View>
              <View className="hr"></View>
            </View>
            <View className="at-col at-col-6 jindouNum">{userInfo.magicBean}</View>
            <Image src={jindou} className="at-col at-col-2 jindou" />
          </View>
        </View>
        {this.renderListContent()}
      </>
    );
  }

  /**
   * 渲染列表
   */
  renderListContent() {
    return <View>{this.renderTabContent()}</View>;
  }

  /**
   * 渲染tab切换
   * @returns
   */
  renderTabContent() {
    const {currentStatus} = this.state;
    const {
      main: {
        items,
        status: {loading},
      },
    } = this.props;
    return (
      <>
        <AtTabs
          current={currentStatus}
          tabList={RECORD_STATUS}
          onClick={this.handleTabChange}
          className="atTab"
        ></AtTabs>
        {this.renderTabListContent(items)}
      </>
    );
  }

  /**
   * 渲染加载效果
   * @returns
   */
  renderLoadingContent() {
    const {
      loading: {status, text, style, textStyle},
    } = this.state;
    return (
      <View className="loadingContent">
        <PageLoading style={style} textStyle={textStyle} />
      </View>
    );
  }

  /**
   * 渲染空内容
   * @returns
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 渲染tab列表内容
   */
  renderTabListContent(items) {
    const {
      main: {
        status: {loading},
      },
    } = this.props;
    const {refresherTriggered} = this.state;
    console.log('index.tsx renderTabListContent loading', loading);
    return (
      <CustomScrollView
        scrollY
        className="scrollViewContent"
        scrollWithAnimation
        onRefresherRefresh={this.handleRreshList}
        onScrollToLower={this.handleScrollLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
        refresherBackground="#f7f7f7"
      >
        {items.length > 0 ? (
          <>
            {items.map((i: any, index: number) => (
              <View key={'tab' + index} className="at-row listRow">
                <View className="at-col at-col-6 listLeft">
                  <View className="listName">{i.content}</View>
                  <View className="listExtra">
                    <View className="listExtraLabel">{i.type ? '获取' : '使用'}时间:</View>
                    <View className="listTime">{moment(i.opTime).format(SECONDS_FORMAT)}</View>
                  </View>
                </View>
                <View className="at-col at-col-6 listRight">
                  <View className="listSuffix" style={{color: i.type ? '#FE6C06' : '#40BE9C'}}>
                    {i.type ? '+' : '-'}
                  </View>
                  <View className="listScore" style={{color: i.type ? '#FE6C06' : '#40BE9C'}}>
                    {i.magicBean}
                  </View>
                </View>
              </View>
            ))}
            <View style={{height: '20vh'}}></View>
          </>
        ) : (
          this.renderEmptyContent()
        )}
      </CustomScrollView>
    );
  }

  /**
   * 下拉刷新
   * @returns
   */
  handleRreshList = () => {
    console.log('goldCoinsDetail handleRreshList');
    const {
      main: {
        page: {pageSize},
      },
    } = this.props;

    const {refresherTriggered} = this.state;
    if (refresherTriggered) return;

    this.setState({
      refresherTriggered: true,
    });

    // 编辑参数
    let params = {
      pageSize,
      pageNum: 0,
      total: 0,
    };

    this.handleQueryItems(params);
  };

  /**
   * 拉到底部加载
   * @returns
   */
  handleScrollLower = () => {
    const {
      main: {page, items},
    } = this.props;

    console.log('index.tsx handleScrollLower page', page);
    if (page.pageNum > 0 && items.length == page.total) {
      return;
    }
    let params = {
      ...page,
      pageNum: page.pageNum + 1,
    };
    this.handleQueryItems(params, {});
  };

  /**
   * 点击切换tab
   */
  handleTabChange = (e) => {
    console.log('index.tsx handleTabChnage e', e);
    const {
      main: {page},
    } = this.props;

    // 编辑参数
    this.setState({
      currentStatus: e,
    });

    // 编辑参数
    let params = {
      pageNum: 0,
      total: 0,
    };
    let type = RECORD_STATUS[e].status;

    this.handleQueryItems(params, {type});
  };

  /**
   * 点击返回
   */
  handleNavBack = () => {
    Taro.navigateBack();
  };

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
